from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
import logging
from datetime import datetime
import os
import asyncio

from .api import video
from .config import STATIC_DIR, STATIC_FILES_DIR
from .models import video as models
from .utils.logger import setup_logger
from .utils.cache_manager import cache_maintenance

# 设置根日志记录器
logger = setup_logger('main')

# 配置 uvicorn 日志
uvicorn_logger = setup_logger('uvicorn')
uvicorn_access_logger = setup_logger('uvicorn.access')
uvicorn_error_logger = setup_logger('uvicorn.error')

# 创建 FastAPI 应用
app = FastAPI(
    title="视频服务系统"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 确保上传目录存在
if not os.path.exists(STATIC_FILES_DIR):
    os.makedirs(STATIC_FILES_DIR)

# 挂载静态文件
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

# 注册路由
app.include_router(video.router, prefix="/api/v1")

@app.on_event("startup")
async def startup():
    """应用启动时执行"""
    logger.info("应用启动")
    # 启动缓存维护任务
    asyncio.create_task(cache_maintenance())

@app.on_event("shutdown")
async def shutdown():
    """应用关闭时执行"""
    logger.info("应用关闭")

@app.middleware("http")
async def log_requests(request: Request, call_next):
    """记录所有HTTP请求"""
    start_time = datetime.now()
    response = await call_next(request)
    duration = (datetime.now() - start_time).total_seconds()
    
    logger.info(
        f"请求处理完成 - "
        f"方法: {request.method}, "
        f"路径: {request.url.path}, "
        f"状态码: {response.status_code}, "
        f"处理时间: {duration:.3f}秒"
    )
    return response

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    """首页路由"""
    logger.info("访问首页")
    # 直接返回 HTML 文件
    with open(os.path.join(STATIC_DIR, "index.html"), "r", encoding="utf-8") as f:
        html_content = f.read()
    return HTMLResponse(content=html_content)

@app.get("/health")
async def health_check():
    """健康检查接口"""
    logger.info("健康检查")
    return {"status": "healthy"}

# 错误处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    logger.error(
        f"全局异常 - "
        f"方法: {request.method}, "
        f"路径: {request.url.path}, "
        f"错误: {exc}",
        exc_info=True
    )
    return {"detail": str(exc)} 